<template>
  <div class="max-w-4xl mx-auto">
    <!-- Instructions Stage -->
    <Transition name="fade" mode="out-in">
      <div v-if="stage === 'instructions'">
        <Card class="shadow-lg">
          <CardHeader class="text-center">
            <CardTitle class="flex items-center justify-center gap-2">
              <Brain class="w-8 h-8 text-purple-600" />
              {{ t("AbstractReasoningTest.title") }}
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-6">
            <div class="text-center space-y-4">
              <p class="text-lg text-slate-600">
                {{ $t("AbstractReasoningTest.subtitle") }}
              </p>
              <div class="bg-purple-50 p-6 rounded-lg space-y-3">
                <h3 class="font-semibold text-purple-900">
                  {{ $t("AbstractReasoningTest.rulesTitle") }}
                </h3>
                <ul class="text-left space-y-2 text-purple-800">
                  <li
                    v-for="(rule, index) in $tm('AbstractReasoningTest.rules')"
                    :key="index"
                  >
                    • {{ rt(rule) }}
                  </li>
                </ul>
              </div>
            </div>
            <div class="flex justify-center">
              <Button
                @click="handleStartTest"
                size="lg"
                class="px-8 bg-purple-600 hover:bg-purple-700"
              >
                {{ t("AbstractReasoningTest.startTest") }}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      <!-- Test Stage -->
      <div v-else-if="stage === 'test' && currentProblemData">
        <Card class="w-full max-w-6xl mx-auto shadow-lg">
          <CardHeader>
            <div class="flex items-center justify-between">
              <CardTitle class="flex items-center gap-2">
                <Brain class="w-6 h-6 text-purple-600" />
                {{ t("AbstractReasoningTest.title") }}
              </CardTitle>
              <div class="flex items-center gap-4">
                <Badge variant="outline" class="flex items-center gap-1">
                  <Clock class="w-4 h-4" />
                  {{ formatTime(timeLeft) }}
                </Badge>
                <Badge variant="secondary">
                  {{ currentProblem + 1 }} / {{ TOTAL_PROBLEMS }}
                </Badge>
              </div>
            </div>
            <Progress
              :model-value="(currentProblem / TOTAL_PROBLEMS) * 100"
              class="mt-2"
            />
          </CardHeader>

          <CardContent class="space-y-8">
            <Transition name="slide" mode="out-in">
              <div :key="currentProblem" class="space-y-6">
                <div class="text-center space-y-2">
                  <h3 class="text-lg font-semibold text-slate-700">
                    {{ t(currentProblemData.description) }}
                  </h3>
                  <p class="text-sm text-purple-600 font-medium">
                    {{ t("AbstractReasoningTest.rulePrefix")
                    }}{{ rt(currentProblemData.rule) }}
                  </p>
                  <Badge
                    variant="outline"
                    :class="{
                      'border-green-300 text-green-700':
                        currentProblemData.difficulty === 'easy',
                      'border-yellow-300 text-yellow-700':
                        currentProblemData.difficulty === 'medium',
                      'border-red-300 text-red-700':
                        currentProblemData.difficulty === 'hard',
                    }"
                  >
                    {{
                      t(
                        `AbstractReasoningTest.difficulty.${currentProblemData.difficulty}`
                      )
                    }}
                  </Badge>
                </div>

                <div class="bg-slate-50 rounded-lg p-6">
                  <div
                    v-if="currentProblemData.type === 'analogy'"
                    class="flex items-center justify-center gap-6"
                  >
                    <div class="flex items-center gap-4">
                      <div
                        v-html="
                          renderAbstractElement(
                            currentProblemData.premise[0],
                            140
                          )
                        "
                      ></div>
                      <span class="text-2xl font-bold text-slate-600">:</span>
                      <div
                        v-html="
                          renderAbstractElement(
                            currentProblemData.premise[1],
                            140
                          )
                        "
                      ></div>
                    </div>
                    <span class="text-3xl font-bold text-purple-600">::</span>
                    <div class="flex items-center gap-4">
                      <div
                        v-html="
                          renderAbstractElement(
                            currentProblemData.premise[2],
                            140
                          )
                        "
                      ></div>
                      <span class="text-2xl font-bold text-slate-600">:</span>
                      <div
                        class="w-[140px] h-[140px] border-2 border-dashed border-purple-400 rounded-lg flex items-center justify-center bg-purple-50"
                      >
                        <span class="text-4xl text-purple-400">?</span>
                      </div>
                    </div>
                  </div>

                  <div v-else class="flex items-center justify-center gap-4">
                    <TransitionGroup name="list">
                      <div
                        v-for="(element, index) in currentProblemData.premise"
                        :key="index"
                        v-html="renderAbstractElement(element, 140)"
                      ></div>
                    </TransitionGroup>
                    <Transition name="fade">
                      <div class="flex items-center gap-2">
                        <span class="text-2xl text-slate-400">→</span>
                        <div
                          class="w-[140px] h-[140px] border-2 border-dashed border-purple-400 rounded-lg flex items-center justify-center bg-purple-50"
                        >
                          <span class="text-4xl text-purple-400">?</span>
                        </div>
                      </div>
                    </Transition>
                  </div>
                </div>

                <div>
                  <h4
                    class="text-md font-semibold text-slate-700 mb-4 text-center"
                  >
                    {{ $t("AbstractReasoningTest.selectAnswer") }}
                  </h4>
                  <div
                    class="grid grid-cols-2 sm:grid-cols-4 gap-6 max-w-4xl mx-auto"
                  >
                    <div
                      v-for="(option, index) in currentProblemData.options"
                      :key="index"
                    >
                      <Button
                        variant="outline"
                        @click="handleAnswer(index)"
                        :disabled="showFeedback"
                        class="w-full h-48 p-4 transition-all duration-300 flex items-center justify-center"
                        :class="{
                          'bg-green-500 text-white border-green-500 hover:bg-green-600':
                            showFeedback &&
                            index === currentProblemData.correct,
                          'bg-red-500 text-white border-red-500':
                            showFeedback &&
                            index !== currentProblemData.correct &&
                            responses[currentProblem] === index,
                          'hover:bg-purple-50 hover:border-purple-300':
                            !showFeedback,
                        }"
                      >
                        <div
                          v-if="
                            option &&
                            option.length > 0 &&
                            option[0] &&
                            option[0].shapes
                          "
                          v-html="renderAbstractElement(option[0], 160)"
                        ></div>
                        <div
                          v-else
                          class="w-16 h-16 bg-slate-100 border border-slate-300 rounded flex items-center justify-center text-slate-400"
                        >
                          ?
                        </div>
                      </Button>
                    </div>
                  </div>
                </div>

                <Transition name="fade">
                  <div
                    v-if="showFeedback"
                    class="p-4 rounded-lg flex items-center gap-3"
                    :class="{
                      'bg-green-100 text-green-800 border-2 border-green-200':
                        feedbackCorrect,
                      'bg-red-100 text-red-800 border-2 border-red-200':
                        !feedbackCorrect,
                    }"
                  >
                    <CheckCircle v-if="feedbackCorrect" class="w-6 h-6" />
                    <X v-else class="w-6 h-6" />
                    <div>
                      <div class="font-semibold">
                        {{
                          feedbackCorrect
                            ? $t("AbstractReasoningTest.feedback.correct")
                            : $t("AbstractReasoningTest.feedback.wrong")
                        }}
                      </div>
                      <div class="text-sm opacity-90">
                        {{
                          feedbackCorrect
                            ? $t(
                                "AbstractReasoningTest.feedback.correctMessage",
                                { rule: $t(currentProblemData.rule) }
                              )
                            : $t(
                                "AbstractReasoningTest.feedback.wrongMessage",
                                {
                                  correctOption: currentProblemData.correct + 1,
                                  rule: $t(currentProblemData.rule),
                                }
                              )
                        }}
                      </div>
                    </div>
                  </div>
                </Transition>
              </div>
            </Transition>
          </CardContent>
        </Card>
      </div>

      <!-- Results Stage -->
      <div v-else-if="stage === 'results'">
        <Card class="shadow-lg">
          <CardHeader class="text-center">
            <CardTitle class="flex items-center justify-center gap-2">
              <Trophy class="w-8 h-8 text-yellow-600" />
              {{ $t("AbstractReasoningTest.results.title") }}
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-6">
            <div class="text-center space-y-4">
              <div class="text-6xl font-bold text-purple-600">
                {{ accuracy }}%
              </div>
              <p class="text-lg text-slate-600">
                {{
                  t("AbstractReasoningTest.results.summary", {
                    score: score,
                    total: TOTAL_PROBLEMS,
                  })
                }}
              </p>
              <div class="grid grid-cols-2 gap-4 mt-6">
                <div class="bg-purple-50 p-4 rounded-lg">
                  <div class="text-2xl font-bold text-purple-600">
                    {{ score }}
                  </div>
                  <div class="text-sm text-purple-800">
                    {{ t("AbstractReasoningTest.results.correctAnswers") }}
                  </div>
                </div>
                <div class="bg-blue-50 p-4 rounded-lg">
                  <div class="text-2xl font-bold text-blue-600">
                    {{ formatTime(timeUsed) }}
                  </div>
                  <div class="text-sm text-blue-800">
                    {{ t("AbstractReasoningTest.results.timeSpent") }}
                  </div>
                </div>
              </div>
            </div>
            <div class="text-center">
              <p class="text-slate-600">
                {{ t("AbstractReasoningTest.results.conclusion") }}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { useI18n } from "vue-i18n";
import { Brain, Clock, Trophy, Star, CheckCircle, X } from "lucide-vue-next";

const { t, tm, rt } = useI18n();
const emit = defineEmits(["complete"]);

const stage = ref("instructions"); // instructions, test, results
const currentProblem = ref(0);
const problems = ref([]);
const responses = ref([]);
const timeLeft = ref(900);
const startTime = ref(0);
const score = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);

const TOTAL_PROBLEMS = 12;

let timer = null;

const currentProblemData = computed(() => problems.value[currentProblem.value]);
const accuracy = computed(() =>
  Math.round((score.value / TOTAL_PROBLEMS) * 100)
);
const timeUsed = computed(() =>
  Math.round((Date.now() - startTime.value) / 1000)
);

watch(stage, (newStage) => {
  if (newStage === "test") {
    timer = setInterval(() => {
      timeLeft.value -= 1;
      if (timeLeft.value <= 0) {
        handleComplete();
      }
    }, 1000);
  } else {
    if (timer) clearInterval(timer);
  }
});

onMounted(() => {
  return () => {
    if (timer) clearInterval(timer);
  };
});

const shuffleOptions = (options, correctIndex = 0) => {
  if (!Array.isArray(options) || options.length === 0) {
    return { shuffledOptions: options, newCorrectIndex: 0 };
  }
  const shuffled = [...options];
  const correctAnswer = shuffled[correctIndex];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  const newCorrectIndex = shuffled.findIndex(
    (option) => JSON.stringify(option) === JSON.stringify(correctAnswer)
  );
  return {
    shuffledOptions: shuffled,
    newCorrectIndex: newCorrectIndex >= 0 ? newCorrectIndex : 0,
  };
};

const renderShape = (shape, containerSize = 180) => {
  if (!shape) return "";
  const { type, position, size, color, rotation = 0, style = "filled" } = shape;
  const actualSize = size === "small" ? 32 : size === "large" ? 64 : 48;
  const colorValue = { black: "#1f2937", white: "#ffffff", gray: "#6b7280" };
  const strokeColor = color === "white" ? "#1f2937" : colorValue[color];
  const fillColor = style === "outline" ? "transparent" : colorValue[color];
  const strokeDasharray = style === "dashed" ? "6,6" : undefined;
  const x = position.x * containerSize;
  const y = position.y * containerSize;
  const shapeProps = {
    fill: fillColor,
    stroke: strokeColor,
    "stroke-width": style === "filled" ? 0 : 3,
    "stroke-dasharray": strokeDasharray,
    transform: `translate(${x}, ${y}) rotate(${rotation})`,
  };

  const propsToString = (props) => {
    return Object.entries(props)
      .filter(([, value]) => value !== undefined && value !== null)
      .map(([key, value]) => `${key}="${value}"`)
      .join(" ");
  };

  const renderShapeElement = () => {
    const propsStr = propsToString(shapeProps);
    switch (type) {
      case "circle":
        return `<circle cx="0" cy="0" r="${actualSize / 2}" ${propsStr} />`;
      case "square":
        return `<rect x="${-actualSize / 2}" y="${
          -actualSize / 2
        }" width="${actualSize}" height="${actualSize}" ${propsStr} />`;
      case "triangle":
        const h = (actualSize * Math.sqrt(3)) / 2;
        return `<polygon points="0,${-h / 2} ${-actualSize / 2},${h / 2} ${
          actualSize / 2
        },${h / 2}" ${propsStr} />`;
      case "diamond":
        return `<polygon points="0,${-actualSize / 2} ${actualSize / 2},0 0,${
          actualSize / 2
        } ${-actualSize / 2},0" ${propsStr} />`;
      case "cross":
        const thickness = actualSize / 4;
        return `<g ${propsStr}><rect x="${-thickness / 2}" y="${
          -actualSize / 2
        }" width="${thickness}" height="${actualSize}" /><rect x="${
          -actualSize / 2
        }" y="${
          -thickness / 2
        }" width="${actualSize}" height="${thickness}" /></g>`;
      case "star":
        const points = Array.from({ length: 10 }, (_, i) => {
          const r = i % 2 === 0 ? actualSize / 2 : actualSize / 4;
          const angle = (i * Math.PI) / 5;
          return `${r * Math.cos(angle - Math.PI / 2)},${
            r * Math.sin(angle - Math.PI / 2)
          }`;
        }).join(" ");
        return `<polygon points="${points}" ${propsStr} />`;
      case "arrow":
        return `<g ${propsStr}><polygon points="${-actualSize / 3},${
          -actualSize / 4
        } ${actualSize / 3},0 ${-actualSize / 3},${actualSize / 4} ${
          -actualSize / 6
        },0" /></g>`;
      case "line":
        return `<line x1="${-actualSize / 2}" y1="0" x2="${
          actualSize / 2
        }" y2="0" ${propsStr} />`;
      default:
        return `<circle cx="0" cy="0" r="${actualSize / 2}" ${propsStr} />`;
    }
  };

  return `<g>${Array.from(
    { length: shape.count || 1 },
    (_, i) =>
      `<g transform="translate(${i * 6}, ${i * 6})">${renderShapeElement()}</g>`
  ).join("")}</g>`;
};

const renderAbstractElement = (element, size = 160) => {
  if (!element || !element.shapes) return "";
  const svgContent = element.shapes
    .map((shape) => renderShape(shape, size))
    .join("");
  return `<div class="border-2 border-slate-300 rounded-lg bg-white flex items-center justify-center shadow-sm hover:shadow-md transition-shadow" style="width: ${size}px; height: ${size}px;"><svg width="${
    size * 0.9
  }" height="${
    size * 0.9
  }" viewBox="0 0 ${size} ${size}"><g transform="translate(${size / 2}, ${
    size / 2
  })">${svgContent}</g></svg></div>`;
};

const generateAnalogyProblem = (id) => {
  const shapeTypes = ["circle", "square", "triangle", "diamond"];
  const shape1 = shapeTypes[Math.floor(Math.random() * shapeTypes.length)];
  const shape2 = shapeTypes.filter((s) => s !== shape1)[
    Math.floor(Math.random() * 3)
  ];
  const premise = [
    {
      shapes: [
        {
          type: shape1,
          position: { x: 0, y: 0 },
          size: "small",
          color: "black",
        },
      ],
    },
    {
      shapes: [
        {
          type: shape1,
          position: { x: 0, y: 0 },
          size: "large",
          color: "black",
        },
      ],
    },
    {
      shapes: [
        {
          type: shape2,
          position: { x: 0, y: 0 },
          size: "small",
          color: "black",
        },
      ],
    },
  ];
  const correctAnswer = {
    shapes: [
      { type: shape2, position: { x: 0, y: 0 }, size: "large", color: "black" },
    ],
  };
  const initialOptions = [
    correctAnswer,
    {
      shapes: [
        {
          type: shape2,
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
        },
      ],
    },
    {
      shapes: [
        {
          type: shape1,
          position: { x: 0, y: 0 },
          size: "large",
          color: "black",
        },
      ],
    },
    {
      shapes: [
        {
          type: shape2,
          position: { x: 0, y: 0 },
          size: "small",
          color: "gray",
        },
      ],
    },
  ];
  const { shuffledOptions, newCorrectIndex } = shuffleOptions(
    initialOptions,
    0
  );
  return {
    id,
    type: "analogy",
    premise,
    question: [correctAnswer],
    options: shuffledOptions.map((option) => [option]),
    correct: newCorrectIndex,
    difficulty: "easy",
    description: t("AbstractReasoningTest.problems.analogy.description"),
    rule: t("AbstractReasoningTest.problems.analogy.rule"),
  };
};

const generateProgressionProblem = (id) => {
  const premise = [
    {
      shapes: [
        {
          type: "arrow",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
          rotation: 0,
        },
      ],
    },
    {
      shapes: [
        {
          type: "arrow",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
          rotation: 60,
        },
      ],
    },
    {
      shapes: [
        {
          type: "arrow",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
          rotation: 120,
        },
      ],
    },
  ];
  const correctAnswer = {
    shapes: [
      {
        type: "arrow",
        position: { x: 0, y: 0 },
        size: "medium",
        color: "black",
        rotation: 180,
      },
    ],
  };
  const initialOptions = [
    correctAnswer,
    {
      shapes: [
        {
          type: "arrow",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
          rotation: 150,
        },
      ],
    },
    {
      shapes: [
        {
          type: "arrow",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
          rotation: 240,
        },
      ],
    },
    {
      shapes: [
        {
          type: "arrow",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
          rotation: 90,
        },
      ],
    },
  ];
  const { shuffledOptions, newCorrectIndex } = shuffleOptions(
    initialOptions,
    0
  );
  return {
    id,
    type: "progression",
    premise,
    question: [correctAnswer],
    options: shuffledOptions.map((option) => [option]),
    correct: newCorrectIndex,
    difficulty: "medium",
    description: t("AbstractReasoningTest.problems.progression.description"),
    rule: t("AbstractReasoningTest.problems.progression.rule"),
  };
};

const generateTransformationProblem = (id) => {
  const premise = [
    {
      shapes: [
        {
          type: "triangle",
          position: { x: -0.2, y: 0 },
          size: "medium",
          color: "black",
          rotation: 0,
        },
        {
          type: "circle",
          position: { x: 0.2, y: 0 },
          size: "small",
          color: "gray",
          style: "outline",
        },
      ],
    },
  ];
  const correctAnswer = {
    shapes: [
      {
        type: "triangle",
        position: { x: 0.2, y: 0 },
        size: "medium",
        color: "black",
        rotation: 0,
      },
      {
        type: "circle",
        position: { x: -0.2, y: 0 },
        size: "small",
        color: "gray",
        style: "outline",
      },
    ],
  };
  const initialOptions = [
    correctAnswer,
    {
      shapes: [
        {
          type: "triangle",
          position: { x: -0.2, y: 0 },
          size: "medium",
          color: "gray",
          rotation: 0,
        },
        {
          type: "circle",
          position: { x: 0.2, y: 0 },
          size: "small",
          color: "black",
          style: "filled",
        },
      ],
    },
    {
      shapes: [
        {
          type: "square",
          position: { x: 0.2, y: 0 },
          size: "medium",
          color: "black",
          rotation: 0,
        },
        {
          type: "diamond",
          position: { x: -0.2, y: 0 },
          size: "small",
          color: "gray",
          style: "outline",
        },
      ],
    },
    {
      shapes: [
        {
          type: "triangle",
          position: { x: -0.2, y: 0 },
          size: "large",
          color: "black",
          rotation: 180,
        },
        {
          type: "circle",
          position: { x: 0.2, y: 0 },
          size: "medium",
          color: "gray",
          style: "outline",
        },
      ],
    },
  ];
  const { shuffledOptions, newCorrectIndex } = shuffleOptions(
    initialOptions,
    0
  );
  return {
    id,
    type: "transformation",
    premise,
    question: [correctAnswer],
    options: shuffledOptions.map((option) => [option]),
    correct: newCorrectIndex,
    difficulty: "hard",
    description: t("AbstractReasoningTest.problems.transformation.description"),
    rule: t("AbstractReasoningTest.problems.transformation.rule"),
  };
};

const generateClassificationProblem = (id) => {
  const premise = [
    {
      shapes: [
        {
          type: "circle",
          position: { x: 0, y: 0 },
          size: "small",
          color: "black",
        },
      ],
    },
    {
      shapes: [
        {
          type: "circle",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
        },
      ],
    },
    {
      shapes: [
        {
          type: "circle",
          position: { x: 0, y: 0 },
          size: "large",
          color: "black",
        },
      ],
    },
  ];
  const correctAnswer = {
    shapes: [
      {
        type: "triangle",
        position: { x: 0, y: 0 },
        size: "medium",
        color: "black",
      },
    ],
  };
  const initialOptions = [
    correctAnswer,
    {
      shapes: [
        {
          type: "circle",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "gray",
        },
      ],
    },
    {
      shapes: [
        {
          type: "circle",
          position: { x: 0, y: 0 },
          size: "small",
          color: "white",
          style: "outline",
        },
      ],
    },
    {
      shapes: [
        {
          type: "circle",
          position: { x: 0, y: 0 },
          size: "medium",
          color: "black",
        },
      ],
    },
  ];
  const { shuffledOptions, newCorrectIndex } = shuffleOptions(
    initialOptions,
    0
  );
  return {
    id,
    type: "classification",
    premise,
    question: [correctAnswer],
    options: shuffledOptions.map((option) => [option]),
    correct: newCorrectIndex,
    difficulty: "easy",
    description: t("AbstractReasoningTest.problems.classification.description"),
    rule: t("AbstractReasoningTest.problems.classification.rule"),
  };
};

const generateSpatialRelationProblem = (id) => {
  const premise = [
    {
      shapes: [
        {
          type: "square",
          position: { x: 0, y: -0.3 },
          size: "large",
          color: "black",
        },
        {
          type: "circle",
          position: { x: 0, y: 0.15 },
          size: "small",
          color: "gray",
        },
      ],
    },
  ];
  const correctAnswer = {
    shapes: [
      {
        type: "circle",
        position: { x: 0, y: -0.3 },
        size: "small",
        color: "gray",
      },
      {
        type: "square",
        position: { x: 0, y: 0.15 },
        size: "large",
        color: "black",
      },
    ],
  };
  const initialOptions = [
    correctAnswer,
    {
      shapes: [
        {
          type: "square",
          position: { x: -0.3, y: 0 },
          size: "large",
          color: "black",
        },
        {
          type: "circle",
          position: { x: 0.15, y: 0 },
          size: "small",
          color: "gray",
        },
      ],
    },
    {
      shapes: [
        {
          type: "triangle",
          position: { x: 0, y: -0.3 },
          size: "large",
          color: "black",
        },
        {
          type: "diamond",
          position: { x: 0, y: 0.15 },
          size: "small",
          color: "gray",
        },
      ],
    },
    {
      shapes: [
        {
          type: "square",
          position: { x: 0, y: -0.3 },
          size: "small",
          color: "black",
        },
        {
          type: "circle",
          position: { x: 0, y: 0.15 },
          size: "large",
          color: "gray",
        },
      ],
    },
  ];
  const { shuffledOptions, newCorrectIndex } = shuffleOptions(
    initialOptions,
    0
  );
  return {
    id,
    type: "spatial_relation",
    premise,
    question: [correctAnswer],
    options: shuffledOptions.map((option) => [option]),
    correct: newCorrectIndex,
    difficulty: "medium",
    description: t(
      "AbstractReasoningTest.problems.spatial_relation.description"
    ),
    rule: t("AbstractReasoningTest.problems.spatial_relation.rule"),
  };
};

const generateProblems = () => {
  const problemGenerators = [
    ...Array(6).fill(generateAnalogyProblem),
    ...Array(3).fill(generateProgressionProblem),
    ...Array(2).fill(generateTransformationProblem),
    generateClassificationProblem,
    generateSpatialRelationProblem,
  ];
  const newProblems = problemGenerators.map((gen, i) => gen(i + 1));
  return newProblems.sort(() => Math.random() - 0.5);
};

const handleStartTest = () => {
  problems.value = generateProblems();
  stage.value = "test";
  startTime.value = Date.now();
};

const handleAnswer = (answerIndex) => {
  const problem = currentProblemData.value;
  if (!problem) return;

  const correct = answerIndex === problem.correct;
  responses.value.push(answerIndex);

  if (correct) {
    score.value += 1;
  }

  feedbackCorrect.value = correct;
  showFeedback.value = true;

  setTimeout(() => {
    showFeedback.value = false;
    if (currentProblem.value < TOTAL_PROBLEMS - 1) {
      currentProblem.value += 1;
    } else {
      handleComplete();
    }
  }, 1500);
};

const handleComplete = () => {
  const result = {
    id: Date.now().toString(),
    testType: "abstract-reasoning",
    score: accuracy.value,
    completedAt: new Date(),
    duration: timeUsed.value,
    details: {
      totalProblems: TOTAL_PROBLEMS,
      correctAnswers: score.value,
      accuracy: accuracy.value,
      averageTimePerProblem: Math.round(timeUsed.value / TOTAL_PROBLEMS),
    },
  };
  stage.value = "results";
  emit("complete", result);
};

const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, "0")}`;
};
</script>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease-out;
}
.slide-enter-from {
  transform: translateX(20px);
  opacity: 0;
}
.slide-leave-to {
  transform: translateX(-20px);
  opacity: 0;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
</style>
